package com.styytech.dadabao.ui.pullrefreshfragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.loopj.android.http.RequestParams;
import com.styytech.dadabao.api.requestresult.ListDataResult;
import com.styytech.dadabao.api.response.AbstractResponseResult;
import com.styytech.dadabao.api.templates.HttpRequest;
import com.styytech.dadabao.bean.ListData;
import com.styytech.dadabao.constant.ConstantsCommon;
import com.styytech.dadabao.exception.ArgumentsException;
import com.styytech.dadabao.exception.RequestException;
import com.styytech.dadabao.utils.AdapterUtils;
import com.styytech.dadabao.utils.CommonUtils;
import com.styytech.dadabao.widge.pulltorefresh.PullToRefreshBase;
import com.styytech.dadabao.widge.pulltorefresh.PullToRefreshListView;

import java.util.LinkedList;

public class ComonGetDataFragment extends BasePullfreshFragment {
    static final String PAGE_SIZE = "10";
    protected BaseAdapter adapter;
    /**
     * 用于存放需要显示的数据
     */
    private LinkedList<Object> showList = new LinkedList<Object>();
    /**
     * 存放刚从服务器获取到的数据
     */
    private LinkedList<Object> getList = new LinkedList<Object>();
    /**
     * 第一页
     */
    protected static int PAGE_NUM_FIRST = 1;
    /**
     * 第几页
     */
    private int newPageNum = 1;
    private int totlePageNum = 0;

    private String dataUrl;

    private int httpType;
    // protected List<NameValuePair> params = null;

    private int adapterType = -1;
    String projectId = null;
    private int intValue = 0;


    InterfaceBaseFragment interfaceBaseFragment;

    private int pulltype = PullToRefreshBase.MODE_PULL_DOWN_TO_REFRESH;


    public void setInterface(InterfaceBaseFragment interfaceBaseFragment) {
        this.interfaceBaseFragment = interfaceBaseFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState, int layoutId) {
        super.onActivityCreated(savedInstanceState);
        dataUrl = getArguments().getString("dataUrl");
        httpType = getArguments().getInt("httpType");
        adapterType = getArguments().getInt("adapterType");
        if (httpType == ConstantsCommon.DATA_SRC_RECORD) {
            projectId = getArguments().getString("value");
        }else if(httpType == ConstantsCommon.DATA_SRC_MESSAGE){
            intValue = getArguments().getInt("value");
        }

        return super.onCreateView(inflater, container, savedInstanceState,
                layoutId);

    }

    @Override
    public void setView(PullToRefreshListView mPullRefreshListView) {
        super.setView(mPullRefreshListView);
    }

    /**
     * 获取数据
     *
     * @param pageNum 获取数据的页数
     */
    protected void getListData(int pageNum) {
        request(dataUrl, null, pageNum + "");
    }

    /**
     * 登陆结果处理
     */
    AbstractResponseResult responseResult = new AbstractResponseResult() {

        @Override
        public void executeSuccess(Object object) {
            ListData listData = (ListData) object;
            newPageNum = listData.getPageNum();
            totlePageNum = listData.getTotlePageNum();
            setListDate(listData.getDataList(), adapterType);
            // testProduct();
            Log.i("INFO", "当前页:" + newPageNum);
            Log.i("INFO", "总页数:" + totlePageNum);
        }

        @Override
        public void executeError(String message, int errorCode) {
            if (errorCode == AbstractResponseResult.SERVER_FAILURE_LOGIN_FAILURE) { // 用户未登录或已过期
                CommonUtils.showToastMsg(getmActivity(), message
                        + "");
                return;
            } else {
                interfaceBaseFragment.setFailureView("" + message);
            }
        }

        @Override
        public void HttpError(String message, int errorCode) {
            CommonUtils.showToastMsg(getmActivity(), message + "");
            interfaceBaseFragment.setFailureView("" + message);
        }
    };

    @SuppressLint("HandlerLeak")
    private void request(String url, String value, String pageNum) {
        RequestParams params = new RequestParams();

        if (httpType == ConstantsCommon.DATA_SRC_RECORD) {
            if (projectId != null) {
                params.put("productId", projectId);
            }
        }else if(httpType == ConstantsCommon.DATA_SRC_MESSAGE){
            if (intValue >= 0) {

                params.put("status", intValue);
            }
        }
        params.put("page.pn", pageNum);
        params.put("page.size", PAGE_SIZE);
        params.put("sidx", "");
        params.put("sord", "asc");

        ListDataResult logResult = new ListDataResult(responseResult, httpType);
        try {
            new HttpRequest(context).doPost(logResult, url, params);
        } catch (ArgumentsException e) {
            e.printStackTrace();
        } catch (RequestException e) {
            e.printStackTrace();
        }

    }

    /**
     * 设置列表数据
     *
     * @param dataType
     */
    private void setListDate(LinkedList<Object> newList, int dataType) {
        interfaceBaseFragment.onRefreshComplete();
        getList.clear(); // 清除数据，防止重复加载
        getList = newList; // 获取服务器数据
        if (getList == null || getList.size() <= 0) {
            setEmptyListDateView(httpType);
            showList.clear();
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
            return;
        }
        if (pulltype == PullToRefreshBase.MODE_PULL_DOWN_TO_REFRESH) {// 如果是下拉刷新，则清除之前数据，全部重新加载
            showList.clear();
        }
        for (Object obj : getList) { // 将服务器获取到的数据，添加到需要显示的数据列表之后
            if (obj != null) {
                showList.addLast(obj);
            }
        }

        if (newPageNum <= PAGE_NUM_FIRST) {
            adapter = AdapterUtils.getAdapter(getmActivity(), showList,// 根据数据类型获取不同的adapter
                    adapterType);
            interfaceBaseFragment.setAdapter(adapter);
        } else {
            if (adapter != null) {
                adapter.notifyDataSetChanged();// 分页加载，只刷新列表数据
            }
        }
    }

    public void setEmptyListDateView(int httpType) {
        interfaceBaseFragment.setEmptyDateShow(httpType);
    }


    /**
     * 下拉刷新
     */
    @Override
    public void pullDownToRefresh() {
        getListData(PAGE_NUM_FIRST);
        pulltype = PullToRefreshBase.MODE_PULL_DOWN_TO_REFRESH;
        super.pullDownToRefresh();
    }

    /**
     * 上拉刷新
     */
    @Override
    public void pullUpToRefresh() {
        if (newPageNum < 0 || totlePageNum < 0) {
            CommonUtils.showToastMsg(getmActivity(), "数据异常");
        }
        if (newPageNum == totlePageNum) {
            CommonUtils.showToastMsg(getmActivity(), "已经是最后一页");
            onRefreshComplete();
        } else {
            getListData(newPageNum + 1);
        }
        pulltype = PullToRefreshBase.MODE_PULL_UP_TO_REFRESH;
        super.pullUpToRefresh();
    }

    @Override
    public void onClick(int position) {
        onItemClick(position);
        super.onClick(position);
    }

    /**
     * 列表点击处理
     */

    public void onItemClick(int position) {
        if (position == 0) {
            return;
        }
        position = position - 1;

        // if (showList.get(position) instanceof Product) { // 理财产品
        //
        // }

    }

    public void adapterNotice() {
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }
}
